package cn.samler.shopapi.Utils;

import cn.samler.shopapi.Config.TencentCaptchaConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class TencentCaptchaUtils {
    private static TencentCaptchaUtils ins;
    private static final String API_HOST = "https://ssl.captcha.qq.com/ticket/verify";
    private final TencentCaptchaConfig config;

    private TencentCaptchaUtils(TencentCaptchaConfig config) {
        this.config = config;
    }

    @PostConstruct
    private void init() {
        ins = new TencentCaptchaUtils(this.config);
    }

    public static TencentCaptchaUtils getInstance() {
        return ins;
    }

    public boolean verify(String ticket, String randStr, String userIp) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet http;
        CloseableHttpResponse resp = null;
        try {
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("aid", this.config.getAppId()));
            params.add(new BasicNameValuePair("AppSecretKey", this.config.getAppSecretKey()));
            params.add(new BasicNameValuePair("Ticket", ticket));
            params.add(new BasicNameValuePair("Randstr", randStr));
            params.add(new BasicNameValuePair("UserIP", userIp));

            http = new HttpGet(new URIBuilder(API_HOST).setParameters(params).build());
            resp = httpclient.execute(http);

            HttpEntity entity = resp.getEntity();
            if (entity != null) {
                String res = EntityUtils.toString(entity);
                JSONObject result = JSON.parseObject(res);
                // 返回码
                int code = result.getInteger("response");
                // 恶意等级
                int evilLevel = result.getInteger("evil_level");
                // 验证成功
                if (code == 1 && evilLevel < 80)
                    return true;

                log.warn("TencentCaptcha check failure: " + result + ", ip: " + userIp);
            }
        } catch (Exception e) {
            log.error("TencentCaptcha Exception: " + e);
        } finally {
            try {
                if (resp != null) resp.close();
            } catch (IOException e) {
                log.warn("TencentCaptcha response close exception: " + e);
            }
        }

        return false;
    }
}
